import Vue from 'vue'
import { login, getUserInfo, logout } from '@/api/modular/system/QHSEloginManage'
import { sysDictTypeTree } from '@/api/modular/system/dictManage'
import { sysMenuChange } from '@/api/modular/system/menuManage'
import { ACCESS_TOKEN, ALL_APPS_MENU, DICT_TYPE_TREE_DATA, LOGIN_SYS } from '@/store/mutation-types'
import { QHSELogin, getQHSEUserInfo } from '@/api/modular/system/QhseToken'

import { welcome } from '@/utils/util'
import store from '../index'
import router from '../../router'
// import { reject } from 'core-js/fn/promise'

const user = {
  state: {
    authId: '',
    email: '',
    idCard: '',
    loginIP: '',
    loginTime: '',
    realName: '',
    mobile: '',
    adminType: '',
    role: '',
    token: '',
    userId: '',
    userName: '',
    secondOrganizationId: '',
    secondOrganizationName: '',
    thirdOrganizationId: '',
    thirdOrganizationName: '',
    currentOrganizationId: '',
    currentOrganizationName: '',
    permissions: [],
    info: {},
    // 下面几个是原本系统中也许不会用了吧
    name: '',
    welcome: '',
    avatar: '',
    buttons: [], // 按钮权限
    roles: []
  },

  mutations: {
    SET_AUTHID: (state, authId) => {
      state.authId = authId
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_IDCARD: (state, idCard) => {
      state.idCard = idCard
    },
    SET_LOGINIP: (state, loginIP) => {
      state.loginIP = loginIP
    },
    SET_LOGINTIME: (state, loginTime) => {
      state.loginTime = loginTime
    },
    SET_REALNAME: (state, realName) => {
      state.realName = realName
    },
    SET_MOBILE: (state, mobile) => {
      state.mobile = mobile
    },
    SET_ADMINTYPE: (state, adminType) => {
      state.adminType = adminType
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_USERNAME: (state, userName) => {
      state.userName = userName
    },
    SET_SECONDORGANIZATIONID: (state, secondOrganizationId) => {
      state.secondOrganizationId = secondOrganizationId
    },
    SET_SECONDORGANIZATIONNAME: (state, secondOrganizationName) => {
      state.secondOrganizationName = secondOrganizationName
    },
    SET_THIRDORGANIZATIONNAME: (state, thirdOrganizationName) => {
      state.thirdOrganizationName = thirdOrganizationName
    },
    SET_THIRDORGANIZATIONID: (state, thirdOrganizationId) => {
      state.thirdOrganizationId = thirdOrganizationId
    },
    SET_CURRENTORGANIZATIONNAME: (state, currentOrganizationName) => {
      state.currentOrganizationName = currentOrganizationName
    },
    SET_CURRENTORGANIZATIONID: (state, currentOrganizationId) => {
      state.currentOrganizationId = currentOrganizationId
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (!response.success) {
            reject(response.message)
            return
          }
          const result = response.data
          Vue.ls.set(ACCESS_TOKEN, result, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(LOGIN_SYS, 2, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result)
          resolve()
        // eslint-disable-next-line handle-callback-err
        }).catch(error => {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject('后端未启动或代理错误')
        })
      })
    },
    // QHSE登录
    QHSELogin (data) {
      return new Promise((resolve, reject) => {
        // 调用QHSELogin接口
        QHSELogin(data).then(response => {
          if (response.success) {
            // 处理QHSE登录成功的情况，设置token等
            const result = response.data
            Vue.ls.set(ACCESS_TOKEN, result, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(LOGIN_SYS, 1, 7 * 24 * 60 * 60 * 1000)
            // commit('token', result)
            resolve()
          }
        }).catch(_error => {
          // 处理网络请求失败的情况
          // eslint-disable-next-line prefer-promise-reject-errors
          reject('后端未启动或代理错误')
        })
      })
    },
    QHSEgetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getQHSEUserInfo().then(res => {
          if (res.success) {
            const data = res.data
            commit('SET_AUTHID', data.authId)
            commit('SET_EMAIL', data.email)
            commit('SET_IDCARD', data.idCard)
            commit('SET_LOGINIP', data.loginIP)
            commit('SET_LOGINTIME', data.loginTime)
            commit('SET_REALNAME', data.realName)
            commit('SET_MOBILE', data.mobile)
            commit('SET_ADMINTYPE', data.adminType)
            commit('SET_ROLE', data.role)
            commit('SET_TOKEN', data.token)
            commit('SET_USERID', data.userId)
            commit('SET_USERNAME', data.userName)
            commit('SET_SECONDORGANIZATIONID', data.secondOrganizationId)
            commit('SET_SECONDORGANIZATIONNAME', data.secondOrganizationName)
            commit('SET_THIRDORGANIZATIONNAME', data.thirdOrganizationId)
            commit('SET_THIRDORGANIZATIONID', data.thirdOrganizationName)
            commit('SET_CURRENTORGANIZATIONNAME', data.currentOrganizationId)
            commit('SET_CURRENTORGANIZATIONID', data.currentOrganizationName)
            commit('SET_PERMISSIONS', data.permissions)
            commit('SET_INFO', data)
            commit('SET_ROLES', 1)
            commit('SET_BUTTONS', data.permissions)
            resolve(data)
          } else {
            // eslint-disable-next-line no-undef
            reject(new Error(data.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          if (response.success) {
            const data = response.data
            console.log('getInfo:', data)
            commit('SET_ADMINTYPE', data.adminType)
            commit('SET_ROLES', 1)
            commit('SET_BUTTONS', data.permissions)
            commit('SET_INFO', data)
            commit('SET_NAME', { name: data.name, welcome: welcome() })
            if (data.avatar != null) {
              commit('SET_AVATAR', process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + data.avatar)
            }
            resolve(data)
          } else {
            // eslint-disable-next-line no-undef
            reject(new Error(data.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_BUTTONS', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_ADMINTYPE', '')
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(LOGIN_SYS)
          Vue.ls.remove(ALL_APPS_MENU)
          Vue.ls.remove(DICT_TYPE_TREE_DATA)
        })
      })
    },

    // 加载所有字典数据
    dictTypeData () {
      return new Promise((resolve, reject) => {
        sysDictTypeTree().then((data) => {
          if (data.success) {
            const result = data.data
            Vue.ls.set(DICT_TYPE_TREE_DATA, result)
            resolve()
          } else {
            // eslint-disable-next-line no-undef
            reject(new Error(data.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 切换应用菜单（小诺1.8原方法）
    MenuChange_Original ({ commit }, application) {
      return new Promise((resolve) => {
        sysMenuChange({ application: application.code }).then((res) => {
          const apps = { 'code': '', 'name': '', 'active': '', 'menu': '' }
          apps.active = true
          apps.menu = res.data
          // eslint-disable-next-line camelcase
          const all_app_menu = Vue.ls.get(ALL_APPS_MENU)
          // eslint-disable-next-line camelcase
          const new_false_all_app_menu = []
          // 先去除所有默认的，以为此时切换的即将成为前端缓存默认的应用
          all_app_menu.forEach(item => {
            if (item.active) {
              item.active = false
            }
            new_false_all_app_menu.push(item)
          })
          // 此时缓存中全部都是不默认的应用
          Vue.ls.set(ALL_APPS_MENU, new_false_all_app_menu)
          apps.name = application.name
          apps.code = application.code
          const applocationR = []
          applocationR.push(apps)
          Vue.ls.set(ALL_APPS_MENU, applocationR)
          resolve(res)
          const antDesignmenus = res.data
          store.dispatch('GenerateRoutes', { antDesignmenus }).then(() => {
            router.addRoutes(store.getters.addRouters)
          })
          // 切换应用刷新整体界面，暂且取消
          // window.location.reload()
        }).catch(() => {
          resolve()
        })
      })
    },

    // 切换应用菜单
    MenuChange ({ commit }, application) {
      return new Promise((resolve, reject) => {
        const appCode = application.code
        console.log(application.code)
        // 缓存获取所有应用
        const allAppMenu = Vue.ls.get(ALL_APPS_MENU)
        // 切换应用
        let appMenu
        allAppMenu.forEach(item => {
          if (item.code === appCode) {
            appMenu = item
            item.active = true
          } else {
            item.active = false
          }
        })
        // 如果找不到
        if (!appMenu) {
          reject(new Error(`找不到应用: ${appCode}`))
          return
        }
        // 找到对应的应用，设置新的缓存
        Vue.ls.set(ALL_APPS_MENU, allAppMenu)
        resolve(appMenu)
        // 切换路由表
        const antDesignmenus = appMenu.menu
        store.dispatch('GenerateRoutes', { antDesignmenus }).then(() => {
          router.addRoutes(store.getters.addRouters)
        })
      })
    }

  }
}

export default user
